package ee.ut.aa.neuraltic.logic;

import org.apache.log4j.Logger;

import ee.ut.aa.neuraltic.model.Board;
import ee.ut.aa.neuraltic.model.Player;

public class Competition {

	private static Logger log = Logger.getLogger( Competition.class );

	private BoardEvaluator eval = new TicEvaluator();

	public Player competition( Player one, Player two, Board board ) {

		log.debug( "Competition starting." );

		int i = 0;
		
		// Just to avoid infinite loop
		while( i++ < 1000 ) {

			if( !eval.isGameOver( board ) )
				one.makeNextMove( board );
			else
				break;

			log.debug( board );
			
			if( !eval.isGameOver( board ) )
				two.makeNextMove( board );
			else
				break;

			log.debug( board );
		}
		
		int winner = eval.findWinner( board );
		
		log.debug( "Competition ended. Winner is player=" + winner );

		if( one.getValue() == winner )
			return one;
		if( two.getValue() == winner )
			return two;
		
		return null;
	}
}
